﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using WFL.Windows;

namespace WFL.Windows.Forms
{
    public class KeyStateEventArgs : EventArgs
    {
        private KBDLLHOOKSTRUCT _keyInfo;

        /// <summary>
        /// 当前按键
        /// </summary>
        public Keys KeyCode
        {
            get { return (Keys)_keyInfo.vkCode; }
        }

        public int ScanCode
        {
            get { return _keyInfo.scanCode; }
        }

        /// <summary>
        /// 从机器开机到消息生成的时间间隔
        /// </summary>
        public int ElapsedTime
        {
            get { return _keyInfo.time; }
        }

        /// <summary>
        /// 当前按键是否是扩展按键
        /// </summary>
        public bool ExtendedKey
        {
            get { return (_keyInfo.flags & Header.Winuser.LLKHF_EXTENDED) == Header.Winuser.LLKHF_EXTENDED; }
        }

        public bool Injected
        {
            get { return (_keyInfo.flags & Header.Winuser.LLKHF_INJECTED) == Header.Winuser.LLKHF_INJECTED; }
        }

        public bool Alt
        {
            get { return (_keyInfo.flags & Header.Winuser.LLKHF_ALTDOWN) == Header.Winuser.LLKHF_ALTDOWN; }
        }

        /// <summary>
        /// 当前按键是否被按下
        /// </summary>
        public bool Down
        {
            get { return !((_keyInfo.flags & Header.Winuser.LLKHF_UP) == Header.Winuser.LLKHF_UP); }
        }

        private Keys _modifiers;
        public Keys Modifiers
        {
            get { return _modifiers; }
        }

        private bool _suppressKeyState;
        public bool SuppressKeyState
        {
            get { return _suppressKeyState; }
            set { _suppressKeyState = value; }
        }

        public KeyStateEventArgs(KBDLLHOOKSTRUCT keyInfo, Keys modifiers)
        {
            _keyInfo = keyInfo;
            _modifiers = (modifiers & Keys.Modifiers);
        }

        public bool IsKeyDown(Keys keyCode)
        {
            return API.User32.GetAsyncKeyState((int)keyCode) < 0;
        }

        public bool IsKeyToggled(Keys keyCode)
        {
            return (API.User32.GetKeyState((int)keyCode) & 0x01) == 1;
        }

        public object GetExtraInfo(Type type)
        {
            if (_keyInfo.dwExtraInfo == IntPtr.Zero)
            {
                return null;
            }
            else
            {
                return Marshal.PtrToStructure(_keyInfo.dwExtraInfo, type);
            }
        }
    }

    public delegate void KeyStateEventHandler(object sender, KeyStateEventArgs e);


}
